package com.office.reader;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDDocumentCatalog;
import org.apache.pdfbox.pdmodel.PDDocumentInformation;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.PDResources;
import org.apache.pdfbox.pdmodel.graphics.xobject.PDXObjectImage;
import org.apache.pdfbox.util.PDFTextStripper;

import com.office.AbstractReader;
import com.office.util.DateUtils;

/**
 * 未使用，原因：pdfbox不支持JBIG2Decode格式的pdf文件
 * 
 * @author h
 * 
 */
public class PdfReader extends AbstractReader {

	/**
	 * 解析pdf文档信息
	 * 
	 * @param pdfPath
	 * @throws Exception
	 */
	public void readPdf(String pdfPath, String imgSavePath) {
		InputStream input = null;
		File pdfFile = new File(pdfPath);
		PDDocument document = null;
		try {
			input = new FileInputStream(pdfFile);
			// 加载 pdf 文档
			document = PDDocument.load(input);

			/** 文档属性信息 **/
			PDDocumentInformation info = document.getDocumentInformation();
			System.out.println("标题:" + info.getTitle());
			System.out.println("主题:" + info.getSubject());
			System.out.println("作者:" + info.getAuthor());
			System.out.println("关键字:" + info.getKeywords());

			System.out.println("应用程序:" + info.getCreator());
			System.out.println("pdf 制作程序:" + info.getProducer());

			System.out.println("作者:" + info.getTrapped());

			System.out.println("创建时间:"
					+ DateUtils.formatDate(info.getCreationDate().getTime()));
			System.out.println("修改时间:"
					+ DateUtils
							.formatDate(info.getModificationDate().getTime()));

			// 获取内容信息
			PDFTextStripper pts = new PDFTextStripper();
			String content = pts.getText(document);
			System.out.println("内容:" + content);

			/** 文档页面信息 **/
			PDDocumentCatalog cata = document.getDocumentCatalog();
			List<?> pages = cata.getAllPages();
			int count = 1;
			for (int i = 0; i < pages.size(); i++) {
				PDPage page = (PDPage) pages.get(i);
				if (null != page) {
					PDResources res = page.findResources();

					// 获取页面图片信息
					Map<?, ?> imgs = res.getImages();
					if (null != imgs) {
						Set<?> keySet = imgs.keySet();
						Iterator<?> it = keySet.iterator();
						while (it.hasNext()) {
							Object obj = it.next();
							PDXObjectImage img = (PDXObjectImage) imgs.get(obj);
							img.write2file(imgSavePath + count);
							count++;
						}
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (null != input)
				try {
					input.close();
				} catch (IOException e) {
					e.printStackTrace();
				}

			if (null != document)
				try {
					document.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
		}
	}

}
